package com.rstrulak.dao;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;

import com.rstrulak.core.dao.GenericDaoImpl;
import com.rstrulak.model.Context;
import com.rstrulak.model.Project;
import com.rstrulak.model.Task;
import com.rstrulak.model.User;

@Repository("taskDao")
public class TaskDaoImpl extends GenericDaoImpl<Task, Long> implements TaskDao {

	@Override
	public List<Task> getTaskListByProject(Project project) {
		DetachedCriteria criteria = createDetachedCriteria();
		criteria.add(Restrictions.eq("project", project));
		return getListByCriteria(criteria);
	}

	@Override
	public List<Task> getTaskListByContext(Context context) {
		DetachedCriteria criteria = createDetachedCriteria();
		criteria.add(Restrictions.eq("context", context));
		return getListByCriteria(criteria);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public void deleteAllTaskFromProject(final Project project) {
		getHibernateTemplate().execute(new HibernateCallback() {

			@Override
			public Object doInHibernate(Session session) throws HibernateException, SQLException {

				StringBuilder hqlQuery = new StringBuilder().append("delete Task t where t.project=:project");

				Query query = session.createQuery(hqlQuery.toString());
				query.setParameter("project", project);
				return query.executeUpdate();
			}

		});
	}

	@Override
	public List<Task> getTaskListByUser(User user) {
		DetachedCriteria criteria = createDetachedCriteria();
		criteria.add(Restrictions.eq("owner", user));
		return getListByCriteria(criteria);
	}

	@Override
	public List<Task> getTaskListByContextAndOwner(Context context, User owner) {
		DetachedCriteria criteria = createDetachedCriteria();
		criteria.add(Restrictions.eq("owner", owner));
		criteria.add(Restrictions.eq("context", context));
		return getListByCriteria(criteria);
	}

}
